﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace OF.Utility
{
    /// <summary>
    /// 短链接帮助类
    /// </summary>
    public class ShortLinkHelper
    {
        public class ShortUrlResponse
        {
           public List<ResponseBody> urls { get; set; }
        }

        public class ResponseBody
        {
            /// <summary>
            /// 短链的可用状态，true：可用、false：不可用。
            /// </summary>
            public bool result { get; set; }
            /// <summary>
            /// 链接的类型，0：普通网页、1：视频、2：音乐、3：活动、5、投票
            /// </summary>
            public int type { get; set; }
            /// <summary>
            /// 原始长链接
            /// </summary>
            public string url_long { get; set; }
            /// <summary>
            /// 短链接
            /// </summary>
            public string url_short { get; set; }
        }

        /// <summary>
        /// 将长链接转换为短连接
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string ShortLongUrl(string url)
        {
            string szReturn = string.Empty;
            if (string.IsNullOrWhiteSpace(url))
            {
                return szReturn;
            }
            var urlEncode = HttpUtility.UrlEncode(url);
            var source = 2849184197;//
            
            string apiUrlFormat = "http://api.weibo.com/2/short_url/shorten.json?source={0}&url_long={1}";
            var requestUrl = string.Format(apiUrlFormat,source, urlEncode);
            var response=HtmlUtility.GetHtml(requestUrl, "get", Encoding.UTF8);
            var oResponse = response.JSONToObject<ShortUrlResponse>();
            if (oResponse.urls.Count>0)
            {
                var oUrlBody = oResponse.urls[0];
                if (oUrlBody.result)
                {
                    szReturn = oUrlBody.url_short;
                }
                else
                {
                    szReturn = url;
                }
            }
            else
            {
                szReturn = url;
            }
            return szReturn;
        }
    
    }
}
